package com.game.commons.utils;

import java.io.File;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


/**
 * XML<-->JAVABEAN
 * @author du'xiang
 *
 */
public class XmlObjectUtil
{
	
	/**
	 * 将XML映射成JAVABEAN
	 * @param str				路径
	 * @param clazz				class对象
	 * @return
	 * @throws JAXBException
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Object>T XmlToJavaBean(String fileName,Class<T> clazz) throws Exception
	{
		JAXBContext jc = JAXBContext.newInstance(clazz);
		Unmarshaller un = jc.createUnmarshaller();
		T t = (T) un.unmarshal(new File(fileName));
		return t;
	}
	
	/**
	 * 将XML映射成JAVABEAN
	 * @param file				路径File
	 * @param clazz				class对象
	 * @return
	 * @throws JAXBException	JAXBE方式解析XML的异常
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Object>T XmlToJavaBean(File file,Class<T> clazz) throws Exception
	{
		JAXBContext jc = JAXBContext.newInstance(clazz);
		Unmarshaller un = jc.createUnmarshaller();
		T t = (T) un.unmarshal(file);
		return t;
	}
	
	/**
	 * javabean转换成XML文件
	 * @param file			路径
	 * @param obj			对象
	 * @throws Exception	异常
	 */
	public static void JavaBeanToXml(String file,Object obj) throws Exception
	{
		JAXBContext jc = JAXBContext.newInstance(obj.getClass());
		Marshaller ms = jc.createMarshaller();
		ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);  
        FileOutputStream stream = new FileOutputStream(file);  
        ms.marshal(obj, stream);
	}
}
